/**
 * @author huangyongjie
 * @date 2019/11/04 18:00
 */

layui.extend({
    select: "perf/perf.select"
}).define(['layer', 'form', 'table', 'laydate', 'jquery', 'formSelects','util','select'], function (exports) {
    let $ = layui.$;
    let layer = layui.layer;
    let form = layui.form;
    let util = layui.util;
    $ = layui.$;
    let select = layui.select;
    let table = layui.table;
    let laydate = layui.laydate;
    let formSelects = layui.formSelects;

    // 选择下单开始月份
/*    laydate.render({
        elem: '#timeSpan'
        , trigger: 'click'
        , range: true
        , format: 'yyyy-MM-dd'
        , value: util.toDateString(new Date(),'yyyy-MM-dd - yyyy-MM-dd')
    });*/
    var nowDate = new Date();
    var monthDateStart = currentMonthFirst(nowDate);
    var monthDateEnd = currentMonthLast(nowDate);
    var startDateDefault = util.toDateString(monthDateStart, "yyyy-MM-dd");
    var endDateDefault = util.toDateString(monthDateEnd, "yyyy-MM-dd");
    laydate.render({
        elem: "#time" //指定元素
        , trigger: 'click'
        , range: true
        , value: startDateDefault + ' - ' + endDateDefault
    });
    // 渲染数据表格
    let cols = [[
        {field: 'batchName', title: '批次名称', align: 'center', width: 100, fixed: 'center'},
        {field: 'coupGrantNum', title: '优惠券发放量', align: 'center', width: 100, fixed: 'center'},
        {field: 'coupReceiveNum', title: '优惠券领取量', align: 'center', width: 100, fixed: 'center'},
        {field: 'coupReceiveRate', title: '领取率', align: 'center',templet: e => rateDealWith(e.coupReceiveNum,e.coupGrantNum)},
        {field: 'coupUseNum', title: '优惠券使用量', align: 'center'},
        {field: 'coupUseRate', title: '使用率', align: 'center',templet: e => rateDealWith(e.coupUseNum,e.coupReceiveNum)},
        {field: 'coupOrderNum', title: '用劵订单量', align: 'center'},
        {field: 'coupNewOrderNum', title: '用劵新单量', align: 'center'},
        {field: 'coupNewOrderRate', title: '用劵拉新率', align: 'center',templet: e => rateDealWith(e.coupNewOrderNum,e.coupOrderNum)},
        {field: 'coutRepeatOrderNum', title: '用劵复购单量', align: 'center'},
        {field: 'coutRepeatOrderRate', title: '用户复购率', align: 'center',templet: e => rateDealWith(e.coutRepeatOrderNum,e.coupOrderNum)},
        {field: 'useCycle', title: '使用周期（天）', align: 'center',templet: e => rateDealWith4(e.useCycle)},
        {field: 'useAvgCycle', title: '使用平均周期（天）', align: 'center',templet: e => rateDealWith3(e,e.useCycle,e.coupOrderNum)},
        {field: 'coupPriceAmount', title: '优惠总金额', align: 'right', templet: e => Fen2Yuan(e.coupPriceAmount)},
        {field: 'orderOriginalPriceAmount', title: '用劵订单原价总额', align: 'right', templet: e => Fen2Yuan(e.orderOriginalPriceAmount)},
        {field: 'roi', title: 'ROI', align: 'center', templet: e => roiFomat(e.orderOriginalPriceAmount,e.coupPriceAmount,e.orderOriginalPriceAmount)}
    ]];

    let tableObj = table.render(
        {
            elem: '#zmn-service-categ-table'
            , url: '/report/coupanalyse/loadData.action'
            , height: "full-100"
            , cols:cols
            , page: true
            , limit: 50
            , limits: [50, 100, 200]
            , where: function () {
                let formData = new FormData(document.querySelector('.search-form'));
                let jsonData = {};
                formData.forEach((value, key) => jsonData[key] = value);
                for (let fieldKey in jsonData) {
                    if (jsonData[fieldKey] === "") {
                        delete jsonData[fieldKey];
                    }
                }
                jsonData["startDate"] = startDateDefault;
                jsonData["endDate"] = endDateDefault + " 23:59:59";;
                return jsonData;
            }()
            , loading: true
            , toolbar: true
            , defaultToolbar: []
            , done: function (res) {
                //添加按钮
                ReportUtil.toobarRightAddButton([{
                    title: '帮助',
                    layEvent: 'CUSTOM_HELP',
                    icon: 'layui-icon-help'
                }, {
                    title: '导出',
                    layEvent: 'CUSTOM_EXPORT',
                    icon: 'layui-icon-export'
                }]);
                ReportUtil.renderTotalRow(res.extData);
            }
            , request: {
                pageName: 'pageIndex' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , response: {
                statusCode: 200
            }
        }
    );

    form.on('submit(form-submit-btn)', function (formObj) {
        //时间区间兼容

        if(formObj.field["time"]){
            let timeSpan = formObj.field["time"].split(' - ');
            formObj.field["time"]='';
            formObj.field["startDate"] = timeSpan[0];
            formObj.field["endDate"] = timeSpan[1]+ " 23:59:59";
        }else{
            formObj.field["startDate"] = "";
            formObj.field["endDate"] = "";
        }
        //修剪提交数据
        for (let fieldKey in formObj.field) {
            if (formObj.field[fieldKey] === "") {
                //delete formObj.field[fieldKey];
            }
        }
        tableObj.reload({
            where: formObj.field,
            page: {curr: 1}
        });
        return false;
    })

    form.on('submit(zmn-form-reset)', function () {
        location.reload();
    });

    //监听头工具事件
    table.on('toolbar(zmn-service-categ-table)', function (obj) {
        switch (obj.event) {
            // 表格导出
            case 'CUSTOM_EXPORT':
                let that = this;
                let ele = that.querySelector('i');
                ReportUtil.toggleLoading(ele);
                that.setAttribute('lay-event', '');
                zmnUtil.download("/report/coupanalyse/export.action", obj.config.where, "优惠卷分析报表" + new Date().toISOString() + '.xlsx', (res) => {
                    that.setAttribute("lay-event", 'CUSTOM_EXPORT');
                    ReportUtil.toggleLoading(ele);
                });
                break;
            case "CUSTOM_HELP":
                ReportUtil.tips(help_content.innerHTML, this);
                break;
            default:
                break;
        }
    });
    formSelects.config(null, {
        keyName: 'text'
    }, false);
    formSelects.btns([]);
    exports('oms_coup_analyse_list');

   /* formSelects.data('activityId', 'server', {
        url: '/report/coupanalyse/getActivityList.action'
    });*/
  /* formSelects.data('memberProductId', 'server', {
        url: '/report/coupanalyse/getMemberProductList.action'
    });*/
    select.render({
        elem: '#activityId',
        url: '/report/coupanalyse/getActivityList.action',
    });

    function Fen2Yuan(numstr) {
        Number.prototype.div = function (arg) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = this.toString().split(".")[1].length
            } catch (e) {
            }
            try {
                t2 = arg.toString().split(".")[1].length
            } catch (e) {
            }
            with (Math) {
                r1 = Number(this.toString().replace(".", ""));
                r2 = Number(arg.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        };
        var num = Number(numstr);
        var yuanMoney =  (num.div(100)).toFixed(2);
        return money_format(yuanMoney);
    }

    function rateDealWith(a,b){
        if(a==""||b==0||b==""){
            return "--";
        }
        var rate = ((a*100)/(b*100))*100;
        return fomatFloat(rate,2)+"%";
    }

    function rateDealWith3(e,a,b){
        if(e.batchName=="汇总"){
            return "--";
        }
        var result =  rateDealWith2(a,b);
        if(!result||result==""){
            return "--";
        }
        return result+"/天";

    }
    function rateDealWith4(a){
        if(!a){
            return "--";
        }
        return a +"/天";
    }
    function rateDealWith2(a,b){
        if(a==""||b==0||b==""){
            return "";
        }
        var rate = ((a*100)/(b*100));
        return fomatFloat(rate,2);
    }
    function fomatFloat(num,n){
        var f = parseFloat(num);
        if(isNaN(f)){
            return false;
        }
        f = Math.round(num*Math.pow(10, n))/Math.pow(10, n); // n 幂
        var s = f.toString();
        var rs = s.indexOf('.');
        //判定如果是整数，增加小数点再补0
        if(rs < 0){
            rs = s.length;
            s += '.';
        }
        while(s.length <= rs + n){
            s += '0';
        }
        return s;
    }
    function roiFomat(a,b,c){
        if(!c){
            return "--";
        }
        if(!a){
            a = 0;
        }
        if(!b){
            b=0;
        }
        var rate = ((a-b)*10000)/(c*100);
        if(!rate||rate==0){
            return "--";
        }
        return fomatFloat(rate,2)+"%";
    }

    function getDateRange(dateNow,intervalDays,bolPastTime){
        let oneDayTime = 24 * 60 * 60 * 1000;
        let list = [];
        let lastDay;

        if(bolPastTime == true){
            lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
            list.push(formateDate(lastDay));
            list.push(formateDate(dateNow));
        }else{
            lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
            list.push(formateDate(dateNow));
            list.push(formateDate(lastDay));
        }
        return list;
    }
    function formateDate(time) {
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let day = time.getDate()

        if (month < 10) {
            month = '0' + month
        }

        if (day < 10) {
            day = '0' + day
        }
        return year + '-' + month + '-' + day + '';
    }
    function money_format(value){
        if(value==0){
            return 0;
        }
        return number_format(value,2,".", ",");
    }

    /**
     * 金额格式化
     * @param number
     * @param decimals
     * @param dec_point
     * @param thousands_sep
     * @returns {string}
     */
    function number_format(number, decimals, dec_point, thousands_sep) {
        /*
        * 参数说明：
        * number：要格式化的数字
        * decimals：保留几位小数
        * dec_point：小数点符号
        * thousands_sep：千分位符号
        * */
        number = (number + '').replace(/[^0-9+-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.ceil(n * k) / k;
            };

        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }

    /**
     * 月初
     * @returns {Date}
     * @constructor
     */
    function currentMonthFirst(date){
        date.setDate(1);
        return date;
    }

    /**
     * 月末
     * @returns {Date}
     */
    function currentMonthLast(date) {
        var currentMonth=date.getMonth();
        var nextMonth=++currentMonth;
        var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
        var oneDay=1000*60*60*24;
        return new Date(nextMonthFirstDay-oneDay);
    }
});
